package api

import (
	"ams/service"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"lib/http"
	http2 "net/http"
)

var AiApi = new(aiApi)

type aiApi struct {
}

func (a aiApi) CallTestHttp(c *gin.Context) {
	in := struct {
		Text string `json:"text"`
	}{}
	if err := c.ShouldBindJSON(&in); err != nil {
		http.BadWithParamsError(c, err)
		return
	}
	err := service.DsService.Call(in.Text, c.Writer)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	http.Ok(c, "我是测试返回的数据")
}

func (a aiApi) CallTestWS(c *gin.Context) {
	var UpGrader = websocket.Upgrader{
		CheckOrigin: func(r *http2.Request) bool {
			return true // 允许跨域（生产环境需限制）
		},
	}
	ws, err := UpGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		http.BadWithErr(c, err)
		return
	}
	go func() {
		defer ws.Close()
		for {
			_, msg, err := ws.ReadMessage()
			if err != nil {
				break
			}
			err = ws.WriteMessage(websocket.TextMessage, msg)
			if err != nil {
				return
			}
		}
	}()
}
